#include "QHandler.h"
#include <QDebug>

QHandler::~QHandler()
{
    qDebug() << __FUNCTION__ << this ;
    stopBackgroundThread();
}

/**
 * @brief QHandler::obtainMessage  获取消息对象
 * @param what
 * @return
 */
QHandlerMessage *QHandler::obtainMessage(int what)
{
    auto message = new (std::nothrow) QHandlerMessage(this);
    if (message)
        message->what = what;
    return message;
}

/**
 * @brief QHandler::sendMessage  发送消息到后台线程中
 * @param message
 */
void QHandler::sendMessage(QHandlerMessage *message)
{
    if (!mWorker.isRunning()) 
    {
        // 将handler移至后台线程中，确保槽函数onMessage()在后台线程中调用
        moveToThread(&mWorker);
        mWorker.start();
    }
    emit sendMessage_signal(message);
}


void QHandler::onMessage(QHandlerMessage *message)
{
    handleMessage(message);
    delete message;
}
